import {createStore, useStore as baseUseStore, Store} from "vuex";
import {InjectionKey} from "vue";

//定义state类型
export interface State {
    token: string
    id: string
}

//定义useStore类型
export const key: InjectionKey<Store<State>> = Symbol('store')

export const store = createStore<State>({
    state () {
        return {
            token: '',
            id: ''
        }
    },
    mutations: {
        setToken (state, token: string) {
            state.token = token
        },
        cleanToken (state) {
            state.token = ''
        },
        setId (state, id: string) {
            state.id = id
        },
        cleanId (state) {
            state.id = ''
        },
        storeToLocalStorage(state) {
            localStorage.setItem('token', state.token);
            localStorage.setItem('id', state.id);
        },
        loadFromLocalStorage(state) {
            // 从localStorage中加载token
            state.token = localStorage.getItem('token') || '';
            state.id = localStorage.getItem('id') || '';

        },
        cleanFromLocalStorage(state) {
            localStorage.setItem('token', '');
            localStorage.setItem('id', '');
            state.token = ''
            state.id = ''
        }

    }
})

//简化useStore的使用
export function useStore () {
    return baseUseStore(key)
}

